package com.simba.server.task;

import com.simba.server.components.CommandExecutor;
import com.simba.server.components.SortCommonDefines;
import org.apache.log4j.Logger;



import com.simba.common.log.LogUtil;

import com.simba.server.commands.impl.fetch.FetchPacketOffByNoUploadCmd;
import com.simba.server.commands.impl.update.RenewSortResultCmd;
import com.simba.server.commands.impl.web.WebPacketOffCmd;
import com.simba.server.commands.impl.web.WebRecycleSlotStateCmd;
import com.simba.server.components.SlotManager;
import com.simba.server.components.SortInfoManager;
import com.simba.server.components.data.SlotInfo;
import com.simba.server.components.data.SortInfo;

public class SortResultOfferTask extends Thread
{
	private final static Logger logger = Logger.getLogger(SortResultOfferTask.class);
	private static final int REQUEST_INTERVAL = 1000;

	public SortResultOfferTask()
	{
		this.setName("Sort-Result-Offer-Task");
	}

	@Override
	public void run()
	{
		while (!Thread.currentThread().isInterrupted())
		{
			try
			{
				this.uploadSortResult();
				Thread.sleep(SortResultOfferTask.REQUEST_INTERVAL);
			}
			catch (Exception ex)
			{
				if (ex instanceof InterruptedException)
				{
					Thread.currentThread().interrupt();
				}
				LogUtil.LogError(SortResultOfferTask.logger,
						"Catch an exception [" + ex.getMessage() + "]");
			}
		}
	}

	private Boolean uploadSortResult()
	{
		Boolean ret = false;

		SortInfo sortInfo = SortInfoManager.getInstance().createSortInfo();

		ret = CommandExecutor.executorSqlCommand(FetchPacketOffByNoUploadCmd.NAME,sortInfo,false);
		if (!ret)
		{
			return ret;
		}

		if (sortInfo.getSortResultId() == 0){
			return ret;
		}

		int droppedSlotId = sortInfo.getDroppedSlotId();
		String slotId = String.valueOf(droppedSlotId);

		// if (SlotManager.getInstance().checkSlotIsTrash(slotId))
		// {
		// return ret;
		// }

		SlotInfo slotInfo = SlotManager.getInstance().getSlotInfo(slotId);
		if (slotInfo == null)
		{
			sortInfo.setUploadFlag(SortCommonDefines.UPLOAD_DEFAULT_FLAG);
			CommandExecutor.executorSqlCommand(RenewSortResultCmd.NAME,sortInfo,false);
			return ret;
		}

		if (sortInfo.getUploadFlag()==SortCommonDefines.UPLOAD_NO_UPLOAD_FLAG)
		{
			return ret;
		}

		if (sortInfo.getUploadFlag()==SortCommonDefines.UPLOAD_ONLY_PACK_FLAG)
		{
			return ret;
		}


		int uploadNum = sortInfo.getUploadNum() + 1;

		String cmdName = null;
		if (sortInfo.getErrorCodePLC() == 0)
		{
			cmdName = WebPacketOffCmd.NAME;
		}
		else
		{
			cmdName = WebRecycleSlotStateCmd.NAME;
		}

		ret = CommandExecutor.executorWebCommand(cmdName,sortInfo,false);

		if (ret)
		{
			sortInfo.setUploadFlag(SortCommonDefines.UPLOAD_SUCCESS_FLAG);
		}
		else
		{
			sortInfo.setUploadFlag(SortCommonDefines.UPLOAD_ERROR_FLAG);
		}

		sortInfo.setUploadNum(uploadNum);

		CommandExecutor.executorSqlCommand(RenewSortResultCmd.NAME,sortInfo,false);
		return ret;
	}
}
